package com.wmh.baseservice.skd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.SnowflakeIdWorker;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.skd.pojo.SkdGroupBuyingActivities;
import com.wmh.baseservice.skd.pojo.SkdLeaderInfo;
import com.wmh.baseservice.skd.pojo.vo.AddGroupBuyingActivitiesReqVO;
import com.wmh.baseservice.skd.pojo.vo.FollowGroupNumAndBrowseNumRespVO;
import com.wmh.baseservice.skd.pojo.vo.NearbyGroupBuyingActiviesRespVO;
import com.wmh.baseservice.skd.pojo.vo.RecycleBinGroupBuyingActivitiesRespVO;
import com.wmh.baseservice.skd.service.SkdGroupBuyingActivitiesService;
import com.wmh.baseservice.skd.mapper.SkdGroupBuyingActivitiesMapper;
import com.wmh.baseservice.skd.service.SkdLeaderInfoService;
import com.wmh.baseservice.skd.service.SkdShoppingCartService;
import com.wmh.baseservice.user.pojo.vo.UsInfoRespVO;
import com.wmh.baseservice.user.service.UsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.wmh.baseservice.skd.utils.VerifyGroupBuyingActivityParams.*;
import static com.wmh.baseservice.skd.utils.VerifyGroupBuyingActivityParams.isValidBonus;

/**
* @author CH
* @description 针对表【skd_group_buying_activities(团购活动表)】的数据库操作Service实现
* @createDate 2024-01-03 09:21:39
*/
@Service
@Slf4j
public class SkdGroupBuyingActivitiesServiceImpl extends ServiceImpl<SkdGroupBuyingActivitiesMapper, SkdGroupBuyingActivities>
    implements SkdGroupBuyingActivitiesService{

    @Resource
    private TokenService tokenService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private SkdLeaderInfoService skdLeaderInfoService;
    @Resource
    private SkdShoppingCartService skdShoppingCartService;
    @Resource
    private SkdGroupBuyingActivitiesMapper skdGroupBuyingActivitiesMapper;
    /**
     * 一键开团
     * @param reqVO 添加团购活动请求体封装
     * @return 返回是否开团成功
     */
    @Override
    @Transactional
    public String startGroupBuying(AddGroupBuyingActivitiesReqVO reqVO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        log.info("开团信息: " + reqVO);

        SkdGroupBuyingActivities skdGroupBuyingActivities = new SkdGroupBuyingActivities();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = dateFormat.parse(reqVO.getStartDate());
            Date endDate = dateFormat.parse(reqVO.getEndDate());
            skdGroupBuyingActivities.setStartDate(startDate);
            skdGroupBuyingActivities.setEndDate(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return ReturnBody.error("日期格式错误!");
        }
        if (StrUtil.isNotBlank(reqVO.getCityDelivery()) && !isValidCityDelivery(reqVO.getCityDelivery())) {
            return ReturnBody.error("同城配送数据格式有误!");
        }

        log.info("commissionSettings: " + reqVO.getCommissionSettings());
        log.info("volumeRewardSettings: " + reqVO.getVolumeRewardSettings());
        log.info("content: " + reqVO.getContent());

        boolean flag = false;
        if (StrUtil.isNotBlank(reqVO.getContent())) {
            try {
                flag = isValidContent(reqVO.getContent());
            } catch (IllegalArgumentException e) {
                return ReturnBody.error(e.getMessage());
            }
        } else {
            skdGroupBuyingActivities.setContent(null);
        }

        if (flag) {
            skdGroupBuyingActivities.setContent(reqVO.getContent());
        }
        if (!isValidBonus(reqVO.getCommissionSettings(), "commissionSettings")){
            return ReturnBody.error("佣金设定数据格式有误!");
        }
        if (!isValidBonus(reqVO.getVolumeRewardSettings(), "volumeRewardSettings")) {
            return ReturnBody.error("达量奖设定数据格式有误!");
        }

        skdGroupBuyingActivities.setUserId(usId)
                .setTitle(reqVO.getTitle())
                .setContent(reqVO.getContent())
                .setGoodsSnapshot(reqVO.getGoodsSnapshot())
                .setCityDelivery(reqVO.getCityDelivery())
                .setPickupPointIds(reqVO.getPickupPointId().stream() // List<Long> 转换为逗号分隔的字符串
                        .map(String::valueOf)
                        .collect(Collectors.joining(",")))
                .setCommissionSettings(reqVO.getCommissionSettings())
                .setVolumeRewardSettings(reqVO.getVolumeRewardSettings());
        skdGroupBuyingActivitiesMapper.insert(skdGroupBuyingActivities);

        // 添加团长信息
        SkdLeaderInfo skdLeaderInfo = new SkdLeaderInfo();
        skdLeaderInfo.setUsId(usId)
                .setGroupBuyingActivityId(skdGroupBuyingActivities.getId())
                .setGroupNo(new SnowflakeIdWorker(1).nextId())
                .setFollowGroupNum(0)
                .setBrowseNum(0);

        skdLeaderInfoService.save(skdLeaderInfo);
        return ReturnBody.success("发布成功!");
    }

    /**
     * 修改团购活动
     * @param groupBuyingActivityId 团购活动id
     * @param reqVO 团购活动请求体
     * @return 返回是否修改成功
     */
    @Override
    public String modifyGroupBuying(Long groupBuyingActivityId, AddGroupBuyingActivitiesReqVO reqVO) {
        SkdGroupBuyingActivities skdGroupBuyingActivities = new SkdGroupBuyingActivities();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = dateFormat.parse(reqVO.getStartDate());
            Date endDate = dateFormat.parse(reqVO.getEndDate());
            skdGroupBuyingActivities.setStartDate(startDate);
            skdGroupBuyingActivities.setEndDate(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return ReturnBody.error("日期格式错误!");
        }
        if (StrUtil.isNotBlank(reqVO.getCityDelivery()) && !isValidCityDelivery(reqVO.getCityDelivery())) {
            return ReturnBody.error("同城配送数据格式有误!");
        }

        // 打印日志输出 commissionSettings 的值
        log.info("commissionSettings: " + reqVO.getCommissionSettings());
        log.info("volumeRewardSettings: " + reqVO.getVolumeRewardSettings());
        log.info("content" + reqVO.getContent());

        boolean flag = false;
        if (StrUtil.isNotBlank(reqVO.getContent())) {
            try {
                flag = isValidContent(reqVO.getContent());
            } catch (IllegalArgumentException e) {
                return ReturnBody.error(e.getMessage());
            }
        } else {
            skdGroupBuyingActivities.setContent(null);
        }

        if (flag) {
            skdGroupBuyingActivities.setContent(reqVO.getContent());
        }
        if (!isValidBonus(reqVO.getCommissionSettings(), "commissionSettings")){
            return ReturnBody.error("佣金设定数据格式有误!");
        }
        if (!isValidBonus(reqVO.getVolumeRewardSettings(), "volumeRewardSettings")) {
            return ReturnBody.error("达量奖设定数据格式有误!");
        }

        skdGroupBuyingActivities
                .setId(groupBuyingActivityId)
                .setTitle(reqVO.getTitle())
                .setContent(reqVO.getContent())
                .setGoodsSnapshot(reqVO.getGoodsSnapshot())
                .setCityDelivery(reqVO.getCityDelivery())
                .setPickupPointIds(reqVO.getPickupPointId().stream() // List<Long> 转换为逗号分隔的字符串
                        .map(String::valueOf)
                        .collect(Collectors.joining(",")))
                .setCommissionSettings(reqVO.getCommissionSettings())
                .setVolumeRewardSettings(reqVO.getVolumeRewardSettings());

        skdGroupBuyingActivitiesMapper.updateById(skdGroupBuyingActivities);
        return ReturnBody.success("修改成功!");
    }

    /**
     * 获取附近的团购活动列表
     * @param pickupPointsAndDistanceList 自提点和距离列表
     * @return 返回附近的团购活动列表
     */
    @Override
    public List<NearbyGroupBuyingActiviesRespVO> getNearbyGroupBuys(List<Map<Long, Double>> pickupPointsAndDistanceList) {
        List<NearbyGroupBuyingActiviesRespVO> respVOList = new ArrayList<>();

        QueryWrapper<SkdGroupBuyingActivities> queryWrapper = new QueryWrapper<>();

        for (Map<Long, Double> map : pickupPointsAndDistanceList) {
            // 遍历每个 map 的键
            for (Long key : map.keySet()) {
                // 构建查询条件，根据自提点ID进行 OR 查询
                queryWrapper.or(wrapper -> wrapper.apply("FIND_IN_SET({0}, pickup_point_ids)", key));
            }
        }

        List<SkdGroupBuyingActivities> skdGroupBuyingActivities = skdGroupBuyingActivitiesMapper.selectList(queryWrapper);

        for (SkdGroupBuyingActivities groupBuyingActivity : skdGroupBuyingActivities) {
            NearbyGroupBuyingActiviesRespVO nearbyGroupBuyingActiviesRespVO = new NearbyGroupBuyingActiviesRespVO();
            UsInfoRespVO usInfo = usInfoService.getAvatarAndNickByUsId(groupBuyingActivity.getUserId());
            FollowGroupNumAndBrowseNumRespVO followGroupNumAndBrowseNumInfo = skdLeaderInfoService.getFollowGroupNumAndBrowseNumByGroupBuyingActivityId(groupBuyingActivity.getId());

            nearbyGroupBuyingActiviesRespVO
                    .setDistance(getShortestDistanceForPickupPoint(pickupPointsAndDistanceList, groupBuyingActivity.getPickupPointIds()))
                    .setGroupBuyingActivityId(groupBuyingActivity.getId())
                    .setAvatarUrl(usInfo.getAvatar())
                    .setNick(usInfo.getNick())
                    .setGroupBuyingActivityTitle(groupBuyingActivity.getTitle())
                    .setGroupBuyingActivityPriceRange(getPriceRangeFromGoodsSnapshot(groupBuyingActivity.getGoodsSnapshot()))
                    .setGoodsImageUrls(getGoodsImagesFromGoodsSnapshot(groupBuyingActivity.getGoodsSnapshot()))
                    .setGoodsVideoUrl(getGoodsVideoFromGoodsSnapshot(groupBuyingActivity.getGoodsSnapshot()))
                    .setFollowGroupNum(followGroupNumAndBrowseNumInfo.getFollowGroupNum())
                    .setBrowseNum(followGroupNumAndBrowseNumInfo.getBrowseNum());

            respVOList.add(nearbyGroupBuyingActiviesRespVO);
        }

        return respVOList;
    }

    /**
     * 结束团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否结束成功
     */
    @Override
    @Transactional
    public String endGroupBuying(Long groupBuyingActivityId) {
        SkdGroupBuyingActivities skdGroupBuyingActivities = new SkdGroupBuyingActivities();
        skdGroupBuyingActivities.setId(groupBuyingActivityId);
        skdGroupBuyingActivities.setIsEnd(1);
        int res = skdGroupBuyingActivitiesMapper.updateById(skdGroupBuyingActivities);
        // 下架用户购物车内商品
        boolean b = skdShoppingCartService.offShelvesShoppingCart(groupBuyingActivityId);
        if (b && res != 0) {
            return ReturnBody.success("结束团购活动成功!");
        } else {
            return ReturnBody.error("结束团购活动失败!请检查重试");
        }
    }

    /**
     * 恢复已结束的团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否恢复成功信息
     */
    @Override
    @Transactional
    public String restoreGroupBuying(Long groupBuyingActivityId) {
        SkdGroupBuyingActivities skdGroupBuyingActivities = new SkdGroupBuyingActivities();
        skdGroupBuyingActivities.setId(groupBuyingActivityId);
        skdGroupBuyingActivities.setIsEnd(0);
        int res = skdGroupBuyingActivitiesMapper.updateById(skdGroupBuyingActivities);
        // 重新上架用户购物车内商品
        boolean b = skdShoppingCartService.onShelvesShoppingCart(groupBuyingActivityId);
        if (b && res != 0) {
            return ReturnBody.success("恢复团购活动成功!");
        } else {
            return ReturnBody.error("恢复团购活动失败!请检查重试");
        }
    }

    /**
     * 查看回收站内团购活动
     * @return 返回回收站团购活动响应体
     */
    @Override
    public List<RecycleBinGroupBuyingActivitiesRespVO> checkRecycleBin(Long usId) {
        List<RecycleBinGroupBuyingActivitiesRespVO> recycleBinGroupBuyingActivitiesRespVOList = new ArrayList<>();
        List<SkdGroupBuyingActivities> skdGroupBuyingActivities = skdGroupBuyingActivitiesMapper.getDeletedGroupBuyingActivities(usId);
        log.info("skdGroupBuyingActivities" + skdGroupBuyingActivities);
        for (SkdGroupBuyingActivities skdGroupBuyingActivity : skdGroupBuyingActivities) {
            RecycleBinGroupBuyingActivitiesRespVO recycleBinGroupBuyingActivitiesRespVO = new RecycleBinGroupBuyingActivitiesRespVO();
            // 根据团购活动id获取跟团人数和浏览人数信息
            FollowGroupNumAndBrowseNumRespVO followGroupNumAndBrowseNumByGroupBuyingActivityId = skdLeaderInfoService.getFollowGroupNumAndBrowseNumByGroupBuyingActivityId(skdGroupBuyingActivity.getId());

            recycleBinGroupBuyingActivitiesRespVO.setGroupBuyingActivityId(skdGroupBuyingActivity.getId())
                    .setGroupBuyingActivityTitle(skdGroupBuyingActivity.getTitle())
                    .setGroupBuyingActivityPriceRange(getPriceRangeFromGoodsSnapshot(skdGroupBuyingActivity.getGoodsSnapshot()))
                    .setGoodsImageUrls(getGoodsImagesFromGoodsSnapshot(skdGroupBuyingActivity.getGoodsSnapshot()))
                    .setFollowGroupNum(followGroupNumAndBrowseNumByGroupBuyingActivityId.getFollowGroupNum())
                    .setBrowseNum(followGroupNumAndBrowseNumByGroupBuyingActivityId.getBrowseNum())
                    .setCreateTime(skdGroupBuyingActivity.getCreateTime());

            recycleBinGroupBuyingActivitiesRespVOList.add(recycleBinGroupBuyingActivitiesRespVO);
        }
        return recycleBinGroupBuyingActivitiesRespVOList;
    }

    /**
     * 删除团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否删除成功信息
     */
    @Override
    @Transactional
    public String deleteGroupBuying(Long groupBuyingActivityId) {
        // 根据团购活动id删除团购活动
        int res = skdGroupBuyingActivitiesMapper.deleteById(groupBuyingActivityId);

        SkdLeaderInfo leaderInfo = skdLeaderInfoService.getLeaderInfoByGroupBuyingActivityId(groupBuyingActivityId);
        // 删除团信息
        boolean bool = skdLeaderInfoService.removeById(leaderInfo.getId());
        // 下架用户购物车内商品
        boolean bl = skdShoppingCartService.offShelvesShoppingCart(groupBuyingActivityId);
        if (res!= 0 && bool && bl) {
            return ReturnBody.success("删除成功!");
        } else {
            return ReturnBody.error("删除失败!");
        }
    }

    /**
     * 根据团购活动id查询团购活动(包含已删除的团购活动)
     * @param groupBuyingActivityId 团购活动id
     * @return 返回团购活动
     */
    @Override
    public SkdGroupBuyingActivities selectGroupBuyingActivity(Long groupBuyingActivityId) {
        return skdGroupBuyingActivitiesMapper.selectGroupBuyingActivity(groupBuyingActivityId);
    }

    /**
     * 恢复(已删除)团购活动
     * @param groupBuyingActivityId 团购活动id
     * @return 返回是否恢复成功信息
     */
    @Override
    @Transactional
    public String recoverActivity(Long groupBuyingActivityId) {
        SkdGroupBuyingActivities res = skdGroupBuyingActivitiesMapper.getDeletedActivityById(groupBuyingActivityId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该团购活动不在回收站!");
        }
        // 恢复(已删除)团购活动
        boolean bool = skdGroupBuyingActivitiesMapper.recoverActivity(res.getId());
        // 恢复(已删除)团信息
        boolean bl = skdLeaderInfoService.recover(res.getId());
        // 恢复用户购物车内商品状态
        boolean b = skdShoppingCartService.onShelvesShoppingCart(res.getId());

        if (bool && bl && b) {
            return ReturnBody.success("恢复成功!");
        } else {
            return ReturnBody.error("恢复失败!");
        }
    }

    // 根据团购活动ID从 pickupPointsAndDistanceList 中获取最短距离
    private Double getShortestDistanceForPickupPoint(List<Map<Long, Double>> pickupPointsAndDistanceList, String pickupPointIds) {

        Set<Long> pickupPointIdSet = Arrays.stream(pickupPointIds.split(","))
                .map(Long::valueOf).collect(Collectors.toSet());

        Double shortestDistance = null;

        // 在 pickupPointsAndDistanceList 中查找最短距离
        for (Map<Long, Double> map : pickupPointsAndDistanceList) {
            // 直接检查 Set 是否包含 pickupPointId
            for (Long pickupPointId : map.keySet()) {
                if (pickupPointIdSet.contains(pickupPointId)) {
                    Double distance = map.get(pickupPointId);
                    if (shortestDistance == null || distance < shortestDistance) {
                        shortestDistance = distance;
                    }
                }
            }
        }

        return shortestDistance;
    }

    /**
     * 解析商品快照获取指定商品划线价
     * @param goodsSnapshot 商品快照
     * @param targetGoodsId 商品id
     * @return 返回商品划线价
     */
    @Override
    public BigDecimal getCrossedPriceFromGoodsSnapshot(String goodsSnapshot, Long targetGoodsId) {
        try {
            // 使用 Jackson 的 ObjectMapper 进行 JSON 解析
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(goodsSnapshot);

            // 遍历每个商品信息
            for (JsonNode productNode : jsonNode) {
                int goodsId = productNode.get("goodsId").asInt();

                // 如果找到目标商品 ID，检查是否存在划线价格参数
                if (goodsId == targetGoodsId) {
                    if (productNode.has("crossed_price") && !productNode.get("crossed_price").isNull()) {
                        return productNode.get("crossed_price").decimalValue();
                    } else {
                        // 如果不存在划线价格参数，返回 -1 或者其他处理方式
                        return BigDecimal.valueOf(-1);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果未找到对应商品 ID，返回 -1 或者其他处理方式
        return BigDecimal.valueOf(-1);
    }

    /**
     * 解析商品快照获取指定商品名称
     * @param goodsSnapshot 商品快照
     * @param targetGoodsId 商品id
     * @return 返回商品名称
     */
    @Override
    public String getGoodsNameFromGoodsSnapshot(String goodsSnapshot, Long targetGoodsId) {
        try {
            // 使用 Jackson 的 ObjectMapper 进行 JSON 解析
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(goodsSnapshot);

            // 遍历每个商品信息
            for (JsonNode productNode : jsonNode) {
                long goodsId = productNode.get("goodsId").asLong();

                // 如果找到目标商品 ID，返回对应的商品名称
                if (goodsId == targetGoodsId) {
                    return productNode.get("name").asText();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 解析商品快照获取价格范围
     * @param goodsSnapshot 商品快照
     * @return 返回价格范围
     */
    @Override
    public String getPriceRangeFromGoodsSnapshot(String goodsSnapshot) {
        JsonArray jsonArray = JsonParser.parseString(goodsSnapshot).getAsJsonArray();

        if (jsonArray.size() > 0) {
            double minPrice = Double.MAX_VALUE;
            double maxPrice = Double.MIN_VALUE;

            for (JsonElement element : jsonArray) {
                JsonObject jsonObject = element.getAsJsonObject();
                if (jsonObject.has("priceRange")) {
                    String priceRange = jsonObject.getAsJsonPrimitive("priceRange").getAsString();

                    // 处理价格范围
                    if (priceRange.contains("-")) {
                        String[] prices = priceRange.split("-");
                        if (prices.length == 2) {
                            double min = Double.parseDouble(prices[0]);
                            double max = Double.parseDouble(prices[1]);

                            // 更新最小价格和最大价格
                            minPrice = Math.min(minPrice, min);
                            maxPrice = Math.max(maxPrice, max);
                        }
                    } else {
                        // 处理单一价格
                        double singlePrice = Double.parseDouble(priceRange);
                        minPrice = Math.min(minPrice, singlePrice);
                        maxPrice = Math.max(maxPrice, singlePrice);
                    }
                }
            }

            // 返回最终的价格范围字符串
            return String.format("%.1f-%.1f", minPrice, maxPrice);
        }

        return null;
    }

    /**
     * 解析商品快照获取商品id
     * @param jsonString 商品快照
     * @return 返回商品id列表
     */
    public List<Long> getGoodsIdsFromGoodsSnapshot(String jsonString) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<Long> goodsIds = null;

        try {
            List<JsonNode> jsonNodes = objectMapper.readValue(jsonString, new TypeReference<List<JsonNode>>() {});
            goodsIds = jsonNodes.stream()
                    .map(jsonNode -> jsonNode.path("goodsId").asLong())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return goodsIds;
    }


    /**
     * 解析商品快照获取商品图片地址
     * @param goodsSnapshot 商品快照
     * @return 返回商品图片地址
     */
    @Override
    public List<String> getGoodsImagesFromGoodsSnapshot(String goodsSnapshot) {
        // 使用 Gson 解析 JSON 字符串
        Gson gson = new Gson();
        JsonArray jsonArray;

        try {
            jsonArray = gson.fromJson(goodsSnapshot, JsonArray.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 检查数组是否包含至少一个元素
        if (jsonArray != null && jsonArray.size() > 0) {
            // 获取第一个元素
            JsonElement firstElement = jsonArray.get(0);

            // 确保元素是一个 JsonObject
            if (firstElement.isJsonObject()) {
                JsonObject jsonObject = firstElement.getAsJsonObject();

                // 获取 goodsImage 字段的值
                JsonArray goodsImageArray = jsonObject.getAsJsonArray("goodsImage");
                String firstGoodsImage = goodsImageArray.get(0).getAsString();
                String secondGoodsImage = goodsImageArray.get(1).getAsString();

                List<String> result = new ArrayList<>();
                result.add(firstGoodsImage);
                result.add(secondGoodsImage);
                return result;
            }
        }

        return null;
    }

    /**
     * 解析商品快照获取商品视频地址
     * @param goodsSnapshot 商品快照
     * @return 返回商品视频地址
     */
    @Override
    public String getGoodsVideoFromGoodsSnapshot(String goodsSnapshot) {
        // 使用 Gson 解析 JSON 字符串
        Gson gson = new Gson();
        JsonArray jsonArray;

        try {
            jsonArray = gson.fromJson(goodsSnapshot, JsonArray.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 检查数组是否包含至少一个元素
        if (jsonArray != null && jsonArray.size() > 0) {
            // 获取第一个元素
            JsonElement firstElement = jsonArray.get(0);

            // 确保元素是一个 JsonObject
            if (firstElement.isJsonObject()) {
                JsonObject jsonObject = firstElement.getAsJsonObject();

                // 获取 goodsVideo 字段的值
                return jsonObject.get("goodsVideo").getAsString();
            }
        }

        return null;
    }
}